use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use tauri::Builder;
use tauri::{
    menu::{Menu, MenuItem},
    tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent},
    AppHandle, Emitter, Manager, Runtime,
};

//初始化一个全局变量
pub static IS_START_CLIPBOARD_MONITOR: AtomicBool = AtomicBool::new(false);

// 创建系统托盘菜单
fn create_tray_menu<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {
    let show_i = MenuItem::with_id(app, "show", "显示", true, None::<&str>)?;
    let toggle_theme_i = MenuItem::with_id(app, "toggle_theme", "切换主题", true, None::<&str>)?;
    let quit_i = MenuItem::with_id(app, "quit", "退出", true, None::<&str>)?;
    let menu = Menu::with_items(app, &[&show_i, &toggle_theme_i, &quit_i])?;
    let _tray = TrayIconBuilder::with_id("com.clipmate.dev")
        .tooltip("ClipMate")
        .icon(app.default_window_icon().unwrap().clone())
        .menu(&menu)
        .on_menu_event(move |app, event| match event.id.as_ref() {
            "show" => {
                if let Some(window) = app.get_webview_window("main") {
                    let _ = window.show();
                    let _ = window.set_focus();
                }
            }
            "toggle_theme" => {
                if let Some(window) = app.get_webview_window("main") {
                    let _ = window.emit("toggle-theme", ());
                }
            }
            "quit" => {
                app.exit(0);
            }
            _ => {}
        })
        // 禁用鼠标左键点击图标显示托盘菜单
        .show_menu_on_left_click(false)
        .on_tray_icon_event(|tray, event| match event {
            TrayIconEvent::Click {
                id: _,
                position: _,
                rect: _,
                button,
                button_state,
            } => {
                if button == MouseButton::Left && button_state == MouseButtonState::Up {
                    if let Some(window) = tray.app_handle().get_webview_window("main") {
                        if !window.is_visible().unwrap_or(false) {
                            let _ = window.show();
                        }
                        let _ = window.unminimize();
                        let _ = window.set_focus();
                    }
                }
            }
            _ => {}
        })
        .build(app)
        .expect("failed to create tray menu");

    Ok(())
}

#[tauri::command]
async fn start_clipboard_monitor<R: Runtime>(app_handle: AppHandle<R>) {
    if IS_START_CLIPBOARD_MONITOR.load(std::sync::atomic::Ordering::SeqCst) {
        return;
    }
    IS_START_CLIPBOARD_MONITOR.store(true, std::sync::atomic::Ordering::SeqCst);
    let handle = app_handle.clone();

    thread::spawn(move || {
        let mut clipboard = arboard::Clipboard::new().unwrap();
        let last_content = Arc::new(Mutex::new(String::new()));

        loop {
            thread::sleep(Duration::from_millis(500));
            if let Ok(current_content) = clipboard.get_text() {
                let mut last_content = last_content.lock().unwrap();
                // println!("1={}\n2={}", *last_content, current_content);

                if current_content != *last_content {
                    *last_content = current_content.clone();
                    let _ = handle.emit("clipboard-change", Some(current_content));
                }
            }
        }
    });
}

pub fn run() {
    Builder::default()
        .plugin(tauri_plugin_dialog::init())
        .plugin(tauri_plugin_http::init())
        .plugin(tauri_plugin_store::Builder::new().build())
        .plugin(tauri_plugin_updater::Builder::new().build())
        .plugin(tauri_plugin_sql::Builder::default().build())
        .plugin(tauri_plugin_global_shortcut::Builder::default().build())
        .invoke_handler(tauri::generate_handler![start_clipboard_monitor])
        .plugin(tauri_plugin_opener::init())
        .plugin(tauri_plugin_clipboard_manager::init())
        // .plugin(tauri_plugin_single_instance::init(|app, argv, cwd| {
        //     if let Some(window) = app.get_webview_window("main") {
        //         if !window.is_visible().unwrap_or(false) {
        //             let _ = window.show();
        //         }
        //         let _ = window.unminimize();
        //         let _ = window.set_focus();
        //     }
        // }))
        .on_window_event(|window, event| {
            if let tauri::WindowEvent::CloseRequested { api, .. } = event {
                let _ = window.hide();
                api.prevent_close();
            }
        })
        .setup(|app| {
            let app_handle = app.handle();
            create_tray_menu(&app_handle)?;
            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
